package top.lunarye.modules.file.controller;


import cn.dev33.satoken.annotation.SaCheckLogin;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;
import top.lunarye.annotation.TokenToStaff;
import top.lunarye.modules.file.service.IFileService;
import top.lunarye.modules.staff.entity.Staff;
import top.lunarye.utils.RestResponse;
import top.lunarye.utils.SystemCode;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 文件表  前端控制器
 * </p>
 *
 * @author lunar
 * @since 2021-07-23
 */
@Api(tags = "文件模块")
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    @Qualifier("FileServiceImpl")
    private IFileService fileService;

    @PostMapping("{path}")
    @SaCheckLogin
    @ApiOperation("上传文件")
    public RestResponse uploadFile(@PathVariable String path, MultipartFile file,
                                   @ApiIgnore @TokenToStaff Staff staff) {
        if (!path.equals("image")&&!path.equals("file"))
            return RestResponse.fail(SystemCode.ParameterValidError.getCode(), "暂不支持该类文件的上传");
        return fileService.uploadFile(file, path, staff);
    }

    @GetMapping("name/{fileName}")
    @ApiOperation("通过文件名下载")
    public ResponseEntity<byte[]> download(@PathVariable String fileName,
                                             HttpServletRequest request) {
        return fileService.downLoad(fileName, request);
    }

    @DeleteMapping("{id}")
    @ApiOperation("通过文件id删除文件")
    public RestResponse deleteById(@PathVariable Integer id,
                                   @ApiIgnore @TokenToStaff Staff staff) {
        return fileService.deleteById(id, staff);
    }

    @GetMapping("{id}")
    @ApiOperation("通过文件id下载")
    public ResponseEntity<byte[]> download(@PathVariable Integer id,
                                           HttpServletRequest request) {
        return fileService.downLoad(id, request);
    }
}

